<template>
	<view class="dx-body">
		<view class="dx-tabs-header">
			<view class="dx-tabs flex">
				<view class="dx-tabs-item" :class="{ active: tabIndex == index }" v-for="(item, index) in tabList" :key="index" @click="tabsChange(index)">
					{{ item.label }}
				</view>
				<view class="dx-tabs-item flex items-center" v-permission="'dx-func-admin/config/add'" @click="showLayerForm = true">
					<dx-icon name="plus" size="18"></dx-icon>
					<text>添加配置</text>
				</view>
			</view>
		</view>
		<view class="pt-30px pr-30px pl-15px pb-15px">
			<el-form ref="formRef" :model="form" status-icon :rules="rules" v-loading="loading">
				<template v-for="item in tabFormItem" :key="item._id">
					<!-- 文本 ,文本域，数字-->
					<el-form-item label-width="150px" :label="item.title" :prop="item.name" v-if="['text', 'textarea', 'number'].includes(item.type)">
						<el-input clearable :type="item.type" :placeholder="`请输入${item.title}`" v-model="form[item.name]"></el-input>
					</el-form-item>
					<!-- 加减数字 -->
					<el-form-item label-width="150px" :label="item.title" :prop="item.name" v-else-if="item.type === 'input-number'">
						<el-input-number clearable v-model="form[item.name]"></el-input-number>
					</el-form-item>
					<!-- 数组 -->
					<el-form-item label-width="150px" :label="item.title" :prop="item.name" v-else-if="item.type === 'array'">
						<dx-array v-model="form[item.name]"></dx-array>
					</el-form-item>
					<!-- 单图 -->
					<el-form-item label-width="150px" :label="item.title" :prop="item.name" v-else-if="['image', 'images'].includes(item.type)">
						<dx-upload v-model="form[item.name]" :limit="item.type === 'image' ? 1 : 9"></dx-upload>
					</el-form-item>
					<!-- 富文本 -->
					<el-form-item label-width="150px" :label="item.title" :prop="item.name" v-else-if="item.type === 'editor'">
						<dx-tinymce v-model="form[item.name]"></dx-tinymce>
					</el-form-item>
				</template>

				<el-form-item label-width="150px">
					<el-button type="primary" @click="onSubmit">立即提交</el-button>
					<el-button @click="resetForm">重置</el-button>
				</el-form-item>
			</el-form>
		</view>
		<!-- 表单 -->
		<dx-layer-form v-model="showLayerForm" :modalForm="modalForm" @success="getConfigList"></dx-layer-form>
	</view>
</template>
<script setup lang="ts">
import { computed, provide, reactive, ref } from 'vue';
import { configList, configSave } from '@/uni_modules/dx-admin/api/index';
const tabIndex = ref(0);
const showLayerForm = ref(false);
const tabList = ref<any>([]);
const tabFormOption = ref<any>({});
const formRef = ref<any>();
const loading = ref(false);
const tabFormItem = computed(() => {
	if (tabList.value.length == 0) return [];
	return tabFormOption.value[tabList.value[tabIndex.value].value];
});
// 弹窗表单
const modalForm = reactive<any>({
	title: '添加配置',
	urls: {
		add: 'config/add',
		edit: 'config/edit',
	},
	type: 'add', // add,edit
	fields: [
		{
			label: '配置标题',
			field: 'title',
			rules: [
				{
					required: true,
					message: '配置标题不能为空',
				},
			],
			value: '',
		},
		{
			label: '配置名称',
			field: 'name',
			rules: [
				{
					required: true,
					message: '配置名称不能为空',
				},
			],
			value: '',
		},
		{
			label: '排序',
			field: 'sort',
			value: 0,
			component: {
				name: 'el-input',
				props: {
					type: 'number',
				},
			},
		},
		{
			label: '是否系统配置',
			field: 'is_sys',
			value: 1,
			component: {
				name: 'el-radio-group',
				options: [
					{
						label: '否',
						value: 0,
					},
					{
						label: '是',
						value: 1,
					},
				],
			},
		},
		{
			label: '是否新建分组',
			field: 'group_type',
			value: 1,
			component: {
				name: 'el-radio-group',
				options: [
					{
						label: '否',
						value: 1,
					},
					{
						label: '是',
						value: 2,
					},
				],
			},
		},
		{
			label: '配置分组',
			field: 'group',
			rules: [
				{
					required: true,
					message: '配置名称不能为空',
				},
			],
			value: '',
			component: {
				name: 'el-select',
				props: {
					placeholder: '请选择配置分组',
				},
				options: [],
			},
			formHide: function (row: any) {
				return !(row.group_type != 2);
			}, //boolean | function
		},
		{
			label: '分组标题',
			field: 'group_title',
			rules: [
				{
					required: true,
					message: '分组标题不能为空',
				},
			],
			formHide: function (row: any) {
				return row.group_type != 2;
			},
		},
		{
			label: '分组名称',
			field: 'group_name',
			rules: [
				{
					required: true,
					message: '分组名称不能为空',
				},
			],
			formHide: function (row: any) {
				return row.group_type != 2;
			},
		},
		{
			label: '配置类型',
			field: 'type',
			rules: [
				{
					required: true,
					message: '配置类型不能为空',
				},
			],
			component: {
				name: 'el-select',
				props: {
					placeholder: '请选择配置类型',
				},
				options: [
					{
						label: '文本',
						value: 'text',
					},
					{
						label: '文本域',
						value: 'textarea',
					},
					{
						label: '数字',
						value: 'number',
					},
					{
						label: '加减数字',
						value: 'input-number',
					},
					{
						label: '数组',
						value: 'array',
					},
					{
						label: '单图',
						value: 'image',
					},
					{
						label: '多图',
						value: 'images',
					},
					{
						label: '富文本',
						value: 'editor',
					},
				],
			},
		},
		{
			label: '验证规格',
			field: 'rule',
			component: {
				name: 'el-select',
				props: {
					placeholder: '请选择验证规格',
					multiple: true,
				},
				options: [
					{
						label: '必填',
						value: 'required',
					},
					{
						label: '手机号码',
						value: 'mobile',
					},
					{
						label: '邮箱',
						value: 'email',
					},
				],
			},
		},
	],
	// row [编辑的数据]
});
provide('onBeforeSubmit', function (type: any, data: any) {
	let param: any = {
		type: data.type,
		title: data.title,
		name: data.name,
		sort: data.sort,
		is_sys: data.is_sys,
		rule: data.rule,
	};
	if (data.group_type === 2) {
		//新建分组
		param.group = {
			title: data.group_title,
			name: data.group_name,
		};
	} else {
		let groupIndex = modalForm.fields.findIndex((item: any) => item.field === 'group');
		let row = modalForm.fields[groupIndex].component?.options?.find((item: any) => item.value === data.group);
		param.group = {
			title: row.label,
			name: row.value,
		};
	}
	return param;
});
// 获取配置列表
function getConfigList() {
	configList({ order: 'sort' }).then((res: any) => {
		if (res.code === 1000) {
			if (!res.data || !res.data.length) return;
			// 重置数据
			tabList.value = [];
			tabFormOption.value = {};
			// 生成tab 和 form
			for (let row of res.data) {
				if (tabFormOption.value[row.group.name] === void 0) {
					tabFormOption.value[row.group.name] = [
						{
							...row,
						},
					];
					tabList.value.push({
						label: row.group.title,
						value: row.group.name,
					});
				} else {
					tabFormOption.value[row.group.name].push({
						...row,
					});
				}
			}
			renderFormAndRule(tabList.value[tabIndex.value].value);
			// 更新分组选项
			let groupIndex = modalForm.fields.findIndex((item: any) => item.field === 'group');
			modalForm.fields[groupIndex].component.options = [...tabList.value];
		} else {
			ElMessage.error(res.message);
		}
	});
}
getConfigList();
// 表单
const rules = reactive<any>({});
const form = reactive<any>({});
// 渲染表单字段和规则
function renderFormAndRule(key: string | number) {
	// 清空表单
	Object.keys(form).forEach((item) => {
		Reflect.deleteProperty(form, item);
	});
	// 清空规则
	Object.keys(rules).forEach((item) => {
		Reflect.deleteProperty(rules, item);
	});
	for (let row of tabFormOption.value[key]) {
		// 表单字段
		form[row.name] = row.value || (['number', 'input-number'].includes(row.type) ? 0 : '');
		if (rules[row.name] === void 0) {
			rules[row.name] = [];
		}
		// 表单验证规则
		for (let rule of row.rule) {
			switch (rule) {
				case 'required':
					rules[row.name].push({
						required: true,
						message: row.title + '不能为空',
					});
					break;
				case 'mobile':
					rules[row.name].push({
						pattern: /^1[3456789]\d{9}$/,
						message: '请输入正确的手机号码',
					});
					break;
				case 'email':
					rules[row.name].push({
						pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/,
						message: '请输入正确的邮箱',
					});
					break;
			}
		}
	}
}
// tab 切换
function tabsChange(index: number) {
	tabIndex.value = index;
	renderFormAndRule(tabList.value[index].value);
}
// 提交
function onSubmit() {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			configSave(form)
				.then((res) => {
					if (res.code === 1000) {
						ElMessage.success(res.message);
						getConfigList();
					} else {
						ElMessage.error(res.message);
					}
				})
				.finally(() => {
					loading.value = false;
				});
		}
	});
}
// 重置
function resetForm() {
	formRef.value?.resetFields();
}
</script>
<style lang="scss" scoped>
.dx-tabs-header {
	font-size: 14px;
	background: #e1e6ec;
	border-color: #e1e6ec;
	padding: 15px 15px 0;
	.dx-tabs {
		white-space: nowrap;
		overflow: auto hidden;
		.dx-tabs-item {
			background-color: #ccd3d9;
			color: #6c7884;
			transition: all 0.1s cubic-bezier(0.645, 0.045, 0.355, 1);
			padding: 8px 15px;
			cursor: pointer;
			border-bottom: 1px solid transparent;
			margin-right: 8px;
			border-radius: 3px 3px 0 0;

			&.active {
				border-top-right-radius: 3px;
				border-top-left-radius: 3px;
				background-color: #ffffff;
			}
		}
	}
}
</style>
